<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>学生个人中心 - 教学管理系统</title>
    <style>
        /* 基础样式 */
        body {
            font-family: 'Segoe UI', Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f5f5f5;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            border-radius: 8px;
        }

        /* 导航栏样式 */
        .nav-tabs {
            background: #2c3e50;
            padding: 1rem;
            border-radius: 8px 8px 0 0;
        }
        
        .nav-link {
            color: #ecf0f1;
            padding: 0.8rem 1.5rem;
            margin: 0 0.5rem;
            border-radius: 4px;
            transition: all 0.3s;
        }
        
        .nav-link.active {
            background: #3498db;
            color: white;
        }

        /* 内容区域 */
        .content-section {
            padding: 2rem;
            min-height: 400px;
        }
        
        /* 表格样式 */
        .course-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 1rem;
        }
        
        .course-table th {
            background: #f8f9fa;
            padding: 12px;
            text-align: left;
        }
        
        .course-table td {
            padding: 12px;
            border-bottom: 1px solid #dee2e6;
        }

        /* 新增模态框样式 */
.modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0,0,0,0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1000;
}

.modal-content {
    background: white;
    padding: 2rem;
    border-radius: 8px;
    min-width: 400px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

/* 错误提示样式补充 */
.alert-danger {
    color: #dc3545;
    padding: 8px;
    margin-bottom: 10px;
    border-radius: 4px;
    background: #f8d7da;
    border: 1px solid #f5c6cb;
}
    </style>
</head>
<body>
    <div class="container">
        <nav class="nav-tabs">
            <a href="?section=profile" class="nav-link <?= $activeSection == 'profile' ? 'active' : '' ?>">个人信息</a>
            <a href="?section=enrolled" class="nav-link <?= $activeSection == 'enrolled' ? 'active' : '' ?>">已选课程</a>
            <a href="?section=available" class="nav-link <?= $activeSection == 'available' ? 'active' : '' ?>">可选课程</a>
        </nav>

        <div class="content-section">
            <?php if ($activeSection == 'profile'): ?>
                <!-- 个人信息模块 -->
                <h2>学生信息</h2>
                <div class="profile-info">
                    <p>姓名：<?= htmlspecialchars($studentInfo['Name']) ?></p>
                    <p>学号：<?= $studentInfo['StudentID'] ?></p>
                    <p>院系：<?= htmlspecialchars($departmentName) ?></p>
                    <p>入学时间：<?= $studentInfo['EnrollmentDate'] ?></p>
                    <p>已获学分：<?= $studentInfo['TotalCredits'] ?></p>
                    <!-- 修改密码按钮 -->
                    <button id="changePasswordBtn" class="btn btn-primary">修改密码</button>
                        
                  
                        
                        <br>

                    <button 
                        onclick="location.href='logout.php'" 
                        style="margin-top: 20px; padding: 8px 20px; background: #dc3545; color: white; border: none; border-radius: 4px; cursor: pointer;"
                    >
                        退出登录
                    </button>
                </div>

            <?php elseif ($activeSection == 'enrolled'): ?>
                <!-- 已选课程模块 -->
                <h2>已选课程列表</h2>
                <table class="course-table">
                    <thead>
                        <tr>
                            <th>课程名称</th>
                            <th>学分</th>
                            <th>授课教师</th>
                            <th>成绩</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($enrolledCourses as $course): ?>
                            <tr>
                                <td><?= htmlspecialchars($course['CourseName']) ?></td>
                                <td><?= $course['Credit'] ?></td>
                                <td><?= htmlspecialchars($course['TeacherName']) ?></td>
                                <td><?= $course['Grade'] ?? '未录入' ?></td>
                                <td>
                                    <?php if (empty($course['Grade'])): ?>
                                        <button class="withdraw-btn" 
                                                data-offering="<?= $course['OfferingID'] ?>"
                                                title="点击退课">
                                            退课
                                        </button>
                                    <?php else: ?>
                                        <span class="text-muted">不可退课</span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>

            <?php elseif ($activeSection == 'available'): ?>
                <!-- 可选课程模块 -->
                <h2>可选课程列表</h2>
                <table class="course-table">
                    <thead>
                        <tr>
                            <th>课程名称</th>
                            <th>学分</th>
                            <th>授课教师</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($availableCourses as $course): ?>
                        <tr>
                            <td><?= htmlspecialchars($course['CourseName']) ?></td>
                            <td><?= $course['Credit'] ?></td>
                            <td><?= htmlspecialchars($course['TeacherName']) ?></td>
                            <td>
                                <button class="enroll-btn" data-offering="<?= $course['OfferingID'] ?>">选课</button>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </div>
    </div>

    <div id="passwordModal" class="modal" style="display:none;">
                            <div class="modal-content">
                                <!-- 旧密码验证阶段 -->
                                <div id="oldPasswordSection">
                                    <h3>验证旧密码</h3>
                                    <div class="alert alert-danger" id="oldPasswordError" style="display:none;"></div>
                                    <input type="password" id="oldPassword" placeholder="输入旧密码" class="form-control">
                                    <button onclick="verifyOldPassword()" class="btn btn-primary mt-2">下一步</button>
                                    <button onclick="closeModal()" class="btn btn-secondary mt-2">取消</button>
                                </div>

                                <!-- 新密码设置阶段（初始隐藏） -->
                                <div id="newPasswordSection">
                                    <h3>设置新密码</h3>
                                    <div class="alert alert-danger" id="newPasswordError" style="display:none;"></div>
                                    <input type="password" id="newPassword" placeholder="输入新密码（至少8位）" class="form-control">
                                    <input type="password" id="confirmPassword" placeholder="确认新密码" class="form-control mt-2">
                                    <button onclick="submitNewPassword()" class="btn btn-success mt-2">提交</button>
                                    <button onclick="showSection('oldPasswordSection')" class="btn btn-secondary mt-2">返回</button>
                                </div>
                            </div>
                        </div>

    <script>
        // AJAX选课操作
        document.querySelectorAll('.enroll-btn').forEach(btn => {
        btn.addEventListener('click', function() {
        const offeringID = this.dataset.offering;
        const btn = this;
        btn.disabled = true; // 立即禁用按钮
        btn.textContent = '处理中...';

        fetch('enroll.php', {//向服务器异步发送选课请求
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ offeringID })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('选课成功！');
                location.reload();
            } else {
                throw new Error(data.error || '选课失败');
            }
        })
        .catch(error => {
            alert(error.message);
        })
        .finally(() => {
            btn.disabled = false; // 恢复按钮
            btn.textContent = '选课';
        });
    });
});

document.addEventListener('DOMContentLoaded', () => {
    document.getElementById('newPasswordSection').style.display = 'none';
});

document.querySelectorAll('.withdraw-btn').forEach(btn => {
    btn.addEventListener('click', async function() {
        if (!confirm('确定要退选该课程吗？')) return;

        const offeringID = this.dataset.offering;
        const btn = this;
        btn.disabled = true;
        btn.textContent = '处理中...';

        try {
            const response = await fetch('withdraw.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ offeringID })
            });

            const data = await response.json();
            if (!response.ok) throw data;

            if (data.success) {
                alert('退课成功！');
                location.reload();
            }
        } catch (error) {
            alert(error.error || '退课失败');
        } finally {
            btn.disabled = false;
            btn.textContent = '退课';
        }
    });
});

// 显示/隐藏模态框
document.getElementById('changePasswordBtn').onclick = () => {
    showSection('oldPasswordSection');//首先显示验证旧密码
    document.getElementById('passwordModal').style.display = 'block';//一点修改密码就显示模态框
}

function closeModal() {//关闭修改密码的模态框
    document.getElementById('passwordModal').style.display = 'none';
    clearForm();
}

// 切换显示阶段
function showSection(sectionId) {
    // 隐藏所有阶段
    document.getElementById('oldPasswordSection').style.display = 'none';
    document.getElementById('newPasswordSection').style.display = 'none';
    
    // 显示目标阶段
    document.getElementById(sectionId).style.display = 'block';
}

// 清除输入内容
function clearForm() {
    document.getElementById('oldPassword').value = '';
    document.getElementById('newPassword').value = '';
    document.getElementById('confirmPassword').value = '';
}

// 验证旧密码
async function verifyOldPassword() {
    const oldPassword = document.getElementById('oldPassword').value;
    if (!oldPassword) {
        showError('oldPasswordError', '请输入旧密码');
        return;
    }

    try {
        const response = await fetch('verify_old_password.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ oldPassword })
        });
        const result = await response.json();

        if (result.success) {
            showSection('newPasswordSection');//如果验证成功，切换显示模态到输入新密码
        } else {
            showError('oldPasswordError', result.error || '验证失败');
        }
    } catch (error) {
        showError('oldPasswordError', '网络错误');
    }
}

// 提交新密码
async function submitNewPassword() {
    const newPassword = document.getElementById('newPassword').value;
    const confirmPassword = document.getElementById('confirmPassword').value;

    if (newPassword.length < 8) {
        showError('newPasswordError', '密码至少需要8位');
        return;
    }
    if (newPassword !== confirmPassword) {
        showError('newPasswordError', '两次输入的密码不一致');
        return;
    }

    try {
        const response = await fetch('update_password.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ newPassword })
        });
        const result = await response.json();

        if (result.success) {
            alert('密码修改成功！');
            closeModal();//关闭模态框
            // 可选：自动跳转到登录页
            // window.location.href = 'logout.php'; 
        } else {
            showError('newPasswordError', result.error || '修改失败');
        }
    } catch (error) {
        showError('newPasswordError', '网络错误');
    }
}

// 错误提示工具函数
function showError(elementId, message) {
    const errorDiv = document.getElementById(elementId);
    errorDiv.textContent = message;
    errorDiv.style.display = 'block';
    setTimeout(() => errorDiv.style.display = 'none', 3000);
}
    </script>
</body>
</html>